<template>
	<view class="login">
		<!-- #ifndef H5 -->
		<UniNavBar title="登录" :statusBar="true" :border="false"></UniNavBar>
		<!-- #endif -->
		<view class="headers">
			<view class="logos">
				<image
					src="https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/0tcFZPuDLYmnaa2ae8e7029f07de28acfc7434c9c518.png"
					mode=""></image>
			</view>
			<view class="titles">
				<view>Hi~</view>
				<view>欢迎使用{{ configs.appName }}</view>
			</view>

		</view>
		<view class="bottom">
			<!-- #ifdef MP-WEIXIN -->
			<button @click="beforeLogin(0)" class="loginBtn">
				<!-- <button  @click="getuserinfo" class="loginBtn"> -->
				<image src="https://000000-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20250804/a3dbcc9aca7d3402389b4e7ac61b624d.png"></image>
				手机号快捷登录
			</button>
			<view class="other">其他方式登入</view>
			<!-- #endif -->
			<view class="phoneBtn" @click="beforeLogin(1)">
				<image src="/static/phoneLogin.png"></image>
				手机账号登录
			</view>

		</view>

		<!-- #ifdef H5 -->
		<!-- <view class="register" v-if="iosVerify==1" @click="toRegister">注册账号</view> -->
		<!-- #endif -->
		<view class="agree-model" v-if="showAgree">

			<view class="agree-model-content">
				<view class="title">
					提示
				</view>
				<view class="content">
					请您仔细阅读相关用户协议，点击同意代表您已阅读并同意获取您的手机号登录平台
					<text @click="toAgree">
						《用户服务协议》与《隐私协议》
					</text>
				</view>
				<view class="btns">
					<view class="btn cancle" @click="showAgree = false">取消</view>
					<button class="btn comfire" open-type="getPhoneNumber" @getphonenumber="getuserinfo">同意</button>
				</view>
			</view>
		</view>
		<view class="agree-model" @click.stop="" v-if="showModel">

			<view class="agree-model-content">
				<view class="title">提示</view>

				<view class="content">您在使用{{ configs.appName }}之前需仔细阅读
					<text
						@click="openPrivacyContract">《{{ configs.appName }}隐私保护指引》</text>。如您阅读并同意《{{ configs.appName }}隐私保护指引》请点击同意开始使用{{ configs.appName }}。
				</view>

				<view class="btns">
					<view class="btn cancle" @click="showModel = false">拒绝</view>
					<button class="btn comfire" open-type="agreePrivacyAuthorization"
						@agreeprivacyauthorization="handleAgree">同意</button>
				</view>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<div class="phone_tips">
			该小程序仅对维保公司人员开放,登录需要获取您的手机号用于唯一性识别和通知接收需使用手机号快捷登录或短信验证登录小程序
		</div>
		<!-- #endif -->
	</view>
</template>
<script>
import { userLogin, getOpenid, getCallbackPhone, getTenantInfoByPhone } from '@/apis/login.js';
import { hanleToken } from '@/utils/utils.js';
import { getConfig } from '@/apis/sign.js';
import UniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
export default {
	data() {
		return {
			showAgree: false,
			privacyPopupShow: false,
			showModel: false,
			type: 0,
			code: '',
			openObj: {},
			// 0 微信登录 1手机号登录
			loginType: 0,
		};
	},
	computed: {
		configs() {
			return this.$config;
		}
	},
	async onLoad(os) {
		this.type = os.type || '';
		hanleToken('set', 'roleId', '');
		hanleToken('set', 'refresh_token', '');
		hanleToken('set', 'token', '');
		if (wx.getPrivacySetting) {
			wx.getPrivacySetting({
				success: (res) => {
					console.log(res, '***getPrivacySetting***');
					if (res.needAuthorization) {
						// 需要弹出隐私协议
						this.privacyPopupShow = true;
					} else {
						// 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用隐私接口
					}
				}

			});
		}

		this.code = await this.getCode();
		this.openObj = await this.getCodeInfo(this.code);
	},
	components: {
		UniNavBar
	},
	methods: {
		toRegister() {
			uni.navigateTo({
				url: '/pages/login/accountLogin?register=true'
			});
		},
		beforeLogin(loginType) {
			this.loginType = loginType;
			if (this.privacyPopupShow) {
				this.showModel = true;
			} else {
				this.handleAgree();
			}
		},
		openPrivacyContract() {
			wx.openPrivacyContract({
				// 打开成功
				success: () => { },
				// 打开失败
				fail: () => { },
				complete: () => { }
			});
		},
		handleAgree() {
			this.showModel = false;
			if (this.loginType == 0) {
				this.showAgree = true;
			} else {
				this.handleAccountLogin();
			}
		},

		toAgree() {
			uni.navigateTo({
				url: '/pageModules/pubilc/agreement'
			});
		},

		// 获取openid
		getCodeInfo(code) {
			return new Promise((resolve, reject) => {
				getOpenid({ code }).then(res => {
					if (res.code === 200) {
						resolve(res.data);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						reject(false);
					}
				});
			});
		},
		// 查询手机号拥有的公司列表
		getPhoneList(phone) {
			return new Promise((resolve, reject) => {
				getTenantInfoByPhone({ phone }).then(res => {
					if (res.code === 200) {
						resolve(res.data);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						reject(false);
					}
				});
			});
		},
		// 登入接口
		// getUserTokenTips(openid, userId) {
		// 	return new Promise((resolve, reject) => {
		// 		getUserToken({
		// 			openid,
		// 			userId,
		// 		}).then(res => {
		// 			if (res.code === 200) {
		// 				resolve(res.data)
		// 				hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
		// 				hanleToken('set', 'refresh_token', res.data.refresh_token);
		// 				hanleToken('set', 'userData', res.data);
		// 				this.$store.commit('user/setUserinfo', res.data)
		// 			} else {
		// 				uni.showToast({
		// 					title: res.msg,
		// 					icon: 'none'
		// 				});
		// 				reject(false)
		// 			}
		// 		})
		// 	})
		// },
		// 获取用户号码
		async getuserinfo(e) {
			// let that = this;
			console.log('getuserinfo', e);
			if (this.openObj && e.detail.errMsg === 'getPhoneNumber:ok') {
				this.showAgree = false;
				getCallbackPhone({
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					openid: this.openObj.openid,
				}).then(async res => {
					if (res.code === 200) {
						// let phoneNumber = res.data.phoneNoInfo.phoneNumber || null
						let phoneList = res.data.tenantInfos;
						// hanleToken('set', 'userCompanyInfo', phoneList);
						uni.setStorage({ key: 'userCompanyInfo', data: phoneList });
						if (phoneList.length <= 0) {
							uni.showModal({
								title: '提示',
								content: '手机号尚未加入通讯录无法登入,请联系公司负责人添加您的信息。',
								success: function (res) {
									if (res.confirm) {
										console.log('用户点击确定');
									}
								}
							});
							return;
						}

						uni.showToast({
							title: '授权成功',
							icon: 'none'
						});
						// await this.getUserTokenTips(this.openObj.openid, phoneList[0].userId)
						// 只有一个租户时 直接跳转首页 ,
						if (phoneList.length === 1 && phoneList[0].roleList.length == 1) {
							this.codeLogin(phoneList[0], res.data.phoneNoInfo.phoneNumber);
							// setTimeout(() => {
							// 	uni.reLaunch({
							// 		url: '/pages/home/index'
							// 	});
							// }, 200)
							return;
						}

						setTimeout(() => {
							uni.reLaunch({
								// url: '/pages/login/companySelect?openid=' + this.openObj.openid
								url: '/pages/login/companySelect?phone=' + res.data.phoneNoInfo.phoneNumber + '&type=' + this.type
							});
						}, 200);

						console.log('公司', phoneList);
					}
				});
			}
		},
		// 验证码登录
		codeLogin(obj, phone) {
			const params = {
				grant_type: obj.grant_type ? obj.grant_type : 'phone',
				scope: 'all',
				username: phone,
				password: obj.verificationKey || '',
				tenantId: obj.tenantId || this.config.tenantId
			};
			uni.showLoading({
				title: '登录中'
			});
			console.log(params, 'params');
			userLogin(params)
				.then(async res => {
					console.log(res, '登录接口-login/index-codeLogin');
					try {
						uni.hideLoading();

						uni.showToast({
							title: '登录成功',
							icon: 'none'
						});
						hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
						hanleToken('set', 'refresh_token', res.data.refresh_token);
						hanleToken('set', 'userData', res.data);
						this.$store.commit('user/setUserinfo', res.data);
						uni.reLaunch({
							url: '/pages/home/index'
						});
					} catch (e) {
						console.log('catch', e);
						// TODO handle the exception
					}
				})
				.catch(err => {
					console.log('err', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
					uni.showModal({
						title: '提示',
						content: '登录失败',
						showCancel: false,
						success() { }
					});
				});
		},
		handleAccountLogin() {
			uni.redirectTo({
				url: '/pages/login/accountLogin?openid=' + this.openObj.openid
				// url: `/pages/login/accountLogin?type=${this.type}`
			});
		},
		// test(param) {
		// 	return new Promise((resolve, reject) => {
		// 		wxLogon(param).then(res=>{
		// 			resolve(res)
		// 		}).catch(err=>{
		// 			resolve(err)
		// 		})
		// 	});
		// },
		getCode() {
			let that = this;
			return new Promise((resolve) => {
				uni.login({
					success(res) {
						that.code = res.code;
						console.log(res.code);
						resolve(res.code);
					},
					fail() {
						that.code = '';
						resolve('');
					}
				});
			});
		}
	}
};
</script>

<style lang="scss">
@import './common.scss';

.login {

	.headers {
		display: flex;
		align-items: center;
		margin: 130rpx 0;
		justify-content: center;

		image {
			width: 144rpx;
			height: 144rpx;
		}

		.titles {
			font-size: 34rpx;
			font-weight: 600;
			color: #333;
			display: flex;
			flex-direction: column;

			// align-items: center;
			text {
				height: 50rpx;
				display: flex;
				align-items: center;
			}
		}
	}

	.bottom {
		display: flex;
		flex-direction: column;
		align-items: center;

		.other {
			margin-top: 40rpx;
			color: #999999;
			font-size: 24rpx;
		}

		image {
			width: 44rpx;
			height: 44rpx;
			padding: 0 10rpx;
		}

		.loginBtn {
			color: #fff;
			width: 710rpx;
			height: 80rpx;
			background: #07c160;
			border-radius: 8rpx;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 20rpx 0;
		}

		.phoneBtn {
			color: #FFFFFF;
			width: 710rpx;
			height: 80rpx;
			background: #0091ff;
			border: 2rpx #0091ff solid;
			border-radius: 8rpx;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 10rpx;
		}
	}
}

.register {
	margin-top: 40rpx;
	text-align: center;
	color: #999999;
	font-size: 28rpx;
}

.phone_tips {
	width: 80%;
	color: #999;
	text-align: center;
	position: absolute;
	bottom: 61rpx;
	left: 10%;
}

.agree-model {
	width: 100%;
	height: 100vh;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 99;
	display: flex;
	justify-content: center;
	color: #333;
	background-color: rgba(0, 0, 0, 0.3);

	&-content {
		border-radius: 16rpx;
		width: 550rpx;
		height: 400rpx;
		background-color: #fff;
		margin-top: 40%;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.title {
			width: 100%;
			// border-bottom: 1rpx solid #999;
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
			padding: 20rpx 0;
		}

		.content {
			padding: 30rpx 40rpx;
			font-size: 28rpx;
			flex: 1;
			overflow-y: scroll;

			text {
				text-decoration: underline;
				color: #0091ff;
			}
		}

		.btns {
			display: flex;
			border-top: 1rpx solid #f0f0f0;

			.btn {
				width: 50%;
				padding: 22rpx 0;
				text-align: center;
				font-size: 28rpx;
				line-height: 28rpx;
				background-color: #fff;
				border: none;
				border-radius: 0;

			}

			.btn:after {
				border: none;
				border-radius: 0;
			}

			.cancle {
				color: #666;
			}

			.comfire {
				border-left: 1rpx solid #f0f0f0;
				color: #0091ff;
			}
		}

	}
}
</style>
